package com.aquan.map_jetpack.ui.components.map_component


//import com.mapbox.mapboxsdk.maps.MapView
//import com.mapbox.mapboxsdk.maps.MapboxMap
import android.annotation.SuppressLint
import android.util.Log
import androidx.annotation.NonNull
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.viewinterop.AndroidView
import androidx.lifecycle.viewmodel.compose.viewModel
import com.aquan.map_jetpack.R
import com.aquan.map_jetpack.ui.components.basic.LifecycleEffect
import com.aquan.map_jetpack.viewmodel.MapViewModel
import com.mapbox.android.gestures.MoveGestureDetector
import com.mapbox.android.gestures.StandardScaleGestureDetector
import com.mapbox.geojson.Point
import com.mapbox.mapboxsdk.Mapbox
import com.mapbox.mapboxsdk.camera.CameraPosition
import com.mapbox.mapboxsdk.geometry.LatLng
import com.mapbox.maps.CameraOptions
import com.mapbox.maps.MapView
import com.mapbox.maps.MapboxMap
import com.mapbox.maps.extension.observable.eventdata.MapLoadedEventData
import com.mapbox.maps.extension.style.style
import com.mapbox.maps.plugin.Plugin
import com.mapbox.maps.plugin.animation.easeTo
import com.mapbox.maps.plugin.attribution.attribution
import com.mapbox.maps.plugin.compass.compass
import com.mapbox.maps.plugin.delegates.listeners.OnMapLoadedListener
import com.mapbox.maps.plugin.gestures.*
import com.mapbox.maps.plugin.locationcomponent.LocationComponentPlugin
import com.mapbox.maps.plugin.locationcomponent.OnIndicatorPositionChangedListener
import com.mapbox.maps.plugin.locationcomponent.location
import com.mapbox.maps.plugin.logo.logo
import com.mapbox.maps.plugin.scalebar.ScaleBarPlugin

@Composable
fun MapTest() {
    Box(modifier = Modifier.fillMaxSize()) {

        val mapView = mapDemo()
        AndroidView(factory = {
            mapView
        })
    }
}

@Composable
fun mapDemo(mapViewModel: MapViewModel = viewModel()): MapView {
    val context = LocalContext.current

    var mapbox: MapboxMap? = null

    val point = rememberSaveable {
        mutableStateOf(mapViewModel.point)
    }
    val zoom = rememberSaveable {
        mutableStateOf(8.0)
    }


    val scaleListener = object : OnScaleListener {
        override fun onScale(detector: StandardScaleGestureDetector) {

        }

        override fun onScaleBegin(detector: StandardScaleGestureDetector) {
            /// TODO("Not yet implemented")
        }

        override fun onScaleEnd(detector: StandardScaleGestureDetector) {
            /// TODO("Not yet implemented")
            val zoomVal: Double? = mapbox?.cameraState?.zoom
            if (zoomVal != null) {
                zoom.value = zoomVal
            }
        }

    }

    val moveListener = object : OnMoveListener {
        override fun onMove(detector: MoveGestureDetector): Boolean {
//            TODO("Not yet implemented")
            return false
        }

        override fun onMoveBegin(detector: MoveGestureDetector) {
//            TODO("Not yet implemented")
        }

        override fun onMoveEnd(detector: MoveGestureDetector) {
//            TODO("Not yet implemented")
            val center = mapbox?.cameraState?.center
            if (center != null) {
                point.value = center
            }
        }

    }


    val mapLoad = OnMapLoadedListener {
        Log.i("Aquan", it.begin.toString())

        mapbox?.addOnScaleListener(scaleListener)

        // 地图移动
        mapbox?.addOnMoveListener(moveListener)
    }
    // 定位监听
    val locationChange = OnIndicatorPositionChangedListener {
        //            TODO("Not yet implemented")
    }

    val mapView = remember {
        Mapbox.getInstance(
            context,
            context.getString(R.string.mapbox_access_token)
        )
        MapView(context).apply {
            val mapView = this

            gestures.rotateEnabled = true
            gestures.scrollEnabled = true
            gestures.pitchEnabled = true
            gestures.quickZoomEnabled = true

            // 隐藏logo
            logo.enabled = false
            attribution.enabled = false
            compass.enabled = false
            val scaleBarPlugin: ScaleBarPlugin? =
                getPlugin(Plugin.MAPBOX_SCALEBAR_PLUGIN_ID)
            // 隐藏 比例尺
            scaleBarPlugin?.enabled = false
            mapbox = getMapboxMap()

            val position = CameraPosition.Builder()
                .target(LatLng(28.44554253, 113.45164694))
                .zoom(8.0)
                .build()

            val initialCameraOptions = CameraOptions.Builder()
                .center(point.value)
                .pitch(0.0)
                .zoom(zoom.value)
                .bearing(0.0)
                .build()

            mapbox?.apply {
                setCamera(cameraOptions = initialCameraOptions)

                loadStyle(
                    style("mapbox://styles/yvhuem78/cl2yjhyab001d15p8ip7gbaql") {
                    }
                )

                // 定位插件
                val locationPlugin: LocationComponentPlugin? =
                    getPlugin(Plugin.MAPBOX_LOCATION_COMPONENT_PLUGIN_ID)

                locationPlugin.apply {
                    this?.enabled = true
                    this?.pulsingEnabled = true
                }
//                addOnMapLoadedListener(mapLoad(this, mapView))
                addOnMapLoadedListener(mapLoad)
                /// 定位监听
            }
            location.addOnIndicatorPositionChangedListener(locationChange)


//            mapboxMap.animateCamera(CameraUpdateFactory.newCameraPosition(position), 1)
//            getMapAsync { mapboxMap ->
////                mapboxMap.setStyle(Style.SATELLITE)
//                mapbox = mapboxMap
//
//                mapboxMap.setStyle(
//                    Style.Builder().fromUri("mapbox://styles/yvhuem78/cl2yjhyab001d15p8ip7gbaql")
//                )
//                val position = CameraPosition.Builder()
//                    .target(LatLng(28.44554253, 113.45164694))
//                    .zoom(8.0)
//                    .build()
//
//                mapboxMap.animateCamera(CameraUpdateFactory.newCameraPosition(position), 1)
//
//                mapboxMap.getStyle {
//                    style {
//
//                    }
//                }
//            }
        }
    }


    // Composable生命周期
    LifecycleEffect(
        onStop = {
            Log.i("Aquan", "onStop")
//            mapBox?.removeOnMapLoadedListener(mapLoad(mapBox))
            // 移出地图加载的监听
            mapbox?.removeOnMapLoadedListener(mapLoad)
            // 地图移动
            mapbox?.removeOnMoveListener(moveListener)
            // 缩放
            mapbox?.removeOnScaleListener(scaleListener)
            // 卸载定位监听
            mapView.location.removeOnIndicatorPositionChangedListener(locationChange)
        },
        onCreate = {
            Log.i("Aquan", "onCreate")
        },
        onDestroy = {
//            mapBox?.removeOnMapLoadedListener(mapLoad())
            Log.i("Aquan", "onDestroy")
        },
        onResume = {
            Log.i("Aquan", "onResume")
        }
    )
    return mapView;
}

fun locationChange(): OnIndicatorPositionChangedListener {
    val mapViewModel = {
        MapViewModel()
    }
    Log.i("currentLocation view", mapViewModel.invoke().point.toJson())
    return OnIndicatorPositionChangedListener {
        Log.i("currentLocation", it.toJson())
        mapViewModel.invoke().setPoint(it)
    }
}

// TODO 地图加载监听 加载完成之后可以添加图层样式的内容
@SuppressLint("LogNotTimber")
private fun mapLoad(mapBox: MapboxMap?, mapView: MapView?): OnMapLoadedListener {
//    TODO("Not yet implemented")
    Log.i("===", "地图加载完成")
//    mapView?.location?.addOnIndicatorPositionChangedListener(locationChange())
    return OnMapLoadedListener {
        Log.i("Aquan", it.begin.toString())
    }
}

@Preview
@Composable
fun MapTestPreview() {
    MapTest()
}

